//
//  RootTabBarViewController.m
//  微blog
//
//  Created by Jorn.Wu on 15/8/19.
//  Copyright (c) 2015年 Jorn.Wu(jorn_wza@sina.com). All rights reserved.
//

#import "RootTabBarViewController.h"
#import "BaseNavigationController.h"
#import "ThemeButton.h"
#import "ThemeTabBar.h"
#import "ThemeImageView.h"
#import "ThemeLabel.h"
#import "SinaWeibo.h"
#import "AppDelegate.h"

@interface RootTabBarViewController ()<SinaWeiboRequestDelegate>

@property (nonatomic, strong) ThemeImageView *notifyBgImage;
@property (nonatomic, strong) ThemeLabel *notifyTitle;

@end

@implementation RootTabBarViewController{
    
    ThemeTabBar *_tabBarView;
    
    ThemeImageView *_selectImageView;
    
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        [self addChildViewControllers];
        
        [self creatTabBar];
        [self creatTabBarItems];
        [self creatSelectImageView];
        
        
        /**
         * 定时刷新请求
         */
        [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(refreshNotifyView) userInfo:nil repeats:YES];
        
        
    }
    return  self;
    
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder{
    self = [super initWithCoder:aDecoder];
    if (self) {
        
        [self addChildViewControllers];
        
        [self creatTabBar];
        [self creatTabBarItems];
        [self creatSelectImageView];
        
        
        /**
         * 定时刷新请求
         */
        [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(refreshNotifyView) userInfo:nil repeats:YES];
        
        
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
}


/**
 * 创建自定义可以切换主题的tabbar（覆盖源bar）
 */
- (void)creatTabBar{
    
    //把原tabBar上的按钮移除
    for (UIView *view in self.tabBar.subviews ) {
        
        Class cls = NSClassFromString(@"UITabBarButton");
        if ([view isKindOfClass:cls]) {
            [view removeFromSuperview];
        }
    }

    _tabBarView = [[ThemeTabBar alloc] initWithFrame:self.tabBar.bounds];
    
    /**
     * _tabBarView 继承与imageView，userInteractionEnabled默认为NO，所以一定改为yes，否则点击不响应；
     */
    _tabBarView.userInteractionEnabled = YES;
    
    _tabBarView.imageName = @"mask_navbar.png";
    
    [self.tabBar addSubview:_tabBarView];
}


/**
 * 创建tabbar上的按钮
 */
- (void)creatTabBarItems{
    
    NSArray *imgNames = @[
                          @"home_tab_icon_1.png",
                          @"home_tab_icon_3.png",
                          @"home_tab_icon_4.png",
                          @"home_tab_icon_5.png",
                          ];
    
    
    CGFloat btnW = kScreenWidth * 1.0 / imgNames.count;
    CGFloat btnH = _tabBarView.frame.size.height;
    
    for (int i = 0; i < imgNames.count; i++) {
        
        ThemeButton *btn = [[ThemeButton alloc] initWithFrame:CGRectMake(btnW * i, 0, btnW, btnH)];
        btn.tag = i + 100;
        btn.normalImageName = imgNames[i];
        [btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
        [_tabBarView addSubview:btn];
        
    }
    
}


/**
 * 点击btn的响应方法
 */
- (void)btnAction:(UIButton *)btn{
    
    /**
     * 动画移动select图标
     */
    [UIView beginAnimations:nil context:nil];
    [UIView animateWithDuration:0.5 animations:^{
        _selectImageView.center = btn.center;
    }];
    [UIView commitAnimations];
    
    /**
     * 根据btn的tag修改显示的视图
     */
    self.selectedIndex = btn.tag - 100;
    
}


/**
 * 创建选中标记图标
 */
- (void)creatSelectImageView{
    
    _selectImageView = [[ThemeImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth / 5.f, CGRectGetHeight(self.tabBar.frame))];
    _selectImageView.imageName = @"home_bottom_tab_arrow.png";
    [_tabBarView insertSubview:_selectImageView atIndex:0];
    
}


- (void)addChildViewControllers{
    
    NSArray *childVCTitles = @[@"首页",@"发现",@"我",@"更多"];
    
    NSArray *childVCNames = @[@"HomeSB",@"DiscoverSB",@"ProfileSB",@"MoreSB"];
    
    NSMutableArray *viewControllers = [NSMutableArray array];
    
    for (int i = 0; i < childVCNames.count; i++) {
        
        NSString *name = childVCNames[i];
        NSString *title = childVCTitles[i];
        BaseNavigationController *nav = [self creatChildViewControllerWithSBName:name title:title];
        
        [viewControllers addObject:nav];
        
    }
    
    self.viewControllers = viewControllers;
}

- (BaseNavigationController *)creatChildViewControllerWithSBName:(NSString *)name title:(NSString *)title{
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:name bundle:nil];
    
    BaseNavigationController *nav = [storyboard instantiateInitialViewController];
    nav.backgroudImageName = @"mask_titlebar64.png";
    nav.titlColorName = @"Mask_Title_color";
    nav.title = title;
    
    return nav;
    
}



/*********************************************************************************************/

/**
 ** 网络刷新工作
 **/




/**
 * 刷新工作（通过webo对象）
 */
- (void)refreshNotifyView{
    
    [self getWeibo];
    
}

- (void)getWeibo{
    AppDelegate *delegate = [UIApplication sharedApplication].delegate;
    SinaWeibo *sinaWeibo = delegate.sinaweibo;
    [sinaWeibo requestWithURL:unread_count params:nil httpMethod:@"GET" delegate:self];         //请求参数为默认
    
}

- (void)request:(SinaWeiboRequest *)request didFinishLoadingWithResult:(id)result{
    CGFloat tabBarButtonWidth = kScreenWidth / 5.0;
    
    if (_notifyBgImage == nil) {
        _notifyBgImage = [[ThemeImageView alloc] initWithFrame:CGRectMake(tabBarButtonWidth - 30, 0, 30, 30)];      //第一个按钮右上角
        _notifyBgImage.imageName = @"number_notify_9.png";
        [_tabBarView addSubview:_notifyBgImage];
        
        _notifyTitle = [[ThemeLabel alloc] initWithFrame:_notifyBgImage.bounds];
        _notifyTitle.textAlignment = NSTextAlignmentCenter;
        _notifyTitle.backgroundColor = [UIColor clearColor];
        _notifyTitle.font = [UIFont systemFontOfSize:13];
        _notifyTitle.textColorName = @"Timeline_Notice_color";
        
        [_notifyBgImage addSubview:_notifyTitle];
    }
    NSNumber *status = [result objectForKey:@"status"];
    NSInteger count = [status integerValue];
    
    if (count > 0) {
        _notifyBgImage.hidden = NO;
        if (count >= 100) {
            count = 99;
            _notifyTitle.text = [NSString stringWithFormat:@"%li+",count];
        }else {
            _notifyTitle.text = [NSString stringWithFormat:@"%li",count];
        }
        
        
    }else {
        _notifyBgImage.hidden = YES;
    }
}


/*********************************************************************************************/











- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
